package tests;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

import ClientLogger.ClientLogger;
import client.TelnetClient;
import client.TelnetClientPipelineFactory;
import clientCommunicationHandler.ClientServerMsgHandler;
import clientCommunicationHandler.UserInterfaceMsgHandler;

public class StressThread implements Runnable {
	
	String host;
	int port;
	int id;

	public StressThread( String host, String port , int id)	{
		this.host = host;
		this.port = Integer.parseInt(port);;
		this.id = id;
	}
	
	
	public void run(){
		ClientBootstrap bootstrap = new ClientBootstrap
				(new NioClientSocketChannelFactory
						(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

		//configure the pipe line factory
		bootstrap.setPipelineFactory(new TelnetClientPipelineFactory());

		//start the connection attempt
		ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,port));

		//wait until the connection attempt succeeds or fails.
		Channel channel = future.awaitUninterruptibly().getChannel();
		if(!future.isSuccess()){
			future.getCause().printStackTrace();
			bootstrap.releaseExternalResources();
			return;
		}

		ChannelFuture lastWriteFuture = null;
		TelnetClient.in = new BufferedReader(new InputStreamReader(System.in));
		String line ;
		UserInterfaceMsgHandler userMsgHandler = new UserInterfaceMsgHandler();
		
		
		//register to server
		line = null;
		String threadId = "thread"+Integer.toString(this.id);
		String command = "register\1"+threadId+"\1"+"1234\1\n\0\n";
		lastWriteFuture = channel.write(command);
		
		
		//listen to user
		for(;;){
			
				command ="addThread\1" + threadId +"\1"+"1\1"+"subject\1body\1\n\0\n"; 
				
				lastWriteFuture = channel.write(command);
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
				
				command = "viewThread\1"+threadId+"\1"+"1\1"+"1\1"+"\n\0\n";
				System.out.println(command);
				lastWriteFuture = channel.write(command);
				
				
				//channel.getCloseFuture().awaitUninterruptibly();
				//break;


		}
		
		
		
	}
}
	
	

